<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <!-- <style>
        body {
            background-color: #ffffff;
        }
    </style> -->
</head>

<body>

    <div class="layuimini-container">
        <div class="layuimini-main">
            <form class="layui-form layui-form-pane" action="">
                <fieldset>

                    <div class="layui-form-item">
                        <label class="layui-form-label required">账号</label>
                        <div class="layui-input-block">
                            <input type="text" name="userName" placeholder="请输入用户名" value="" class="layui-input">
                            <!-- <tip>填写新的账号的名称。</tip> -->
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label required">密码</label>
                        <div class="layui-input-block">
                            <!-- <input type="password" name="userPass" placeholder="请输入密码" value="" class="layui-input"> -->
                            <input type="text" name="userPass" placeholder="请输入密码" value="" class="layui-input">
                            <!-- <tip>填写新的账号的密码。</tip> -->
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label required">可管理控数</label>
                        <div class="layui-input-block">
                            <input type="number" name="maxDeviceNum" placeholder="请输入控数" value="1" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label required">备注</label>
                        <div class="layui-input-block">
                            <input type="text" name="beiZhu" placeholder="请输入备注" value="" class="layui-input">
                            <!-- <tip>请输入备注。</tip> -->
                        </div>
                    </div>


                    <!-- <div class="layui-form-item">
                        <label class="layui-form-label">其他选项</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="checkStatus" title="账户开关" checked="" />
                            <input type="checkbox" name="touPing" title="投屏开关" />
                        </div>
                    </div> -->

                    <fieldset>
                        <legend>权限管理</legend>
                        <div id="roleTreeId"></div>
                    </fieldset>

                    <br>

                    <button class="layui-btn" lay-submit value="保存用户" lay-filter="tijiao">保存用户</button>
                </fieldset>
            </form>
        </div>
    </div>

    <script src="/lib/layui/layui.js" charset="utf-8"></script>
    <script src="/lib/axios/axios.js" charset="utf-8"></script>
    <script>

        layui.use(['form'], function () {
            const $ = layui.jquery;
            const form = layui.form;
            const tree = layui.tree;
            const util = layui.util;
            let parentData = parent.data;
            let userUrl = "/user/addUser";
            if (!parentData) {
                layer.alert("未获取到父页面数据")
                let iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            }
            // console.log("parentData", parentData);
            (async () => {
                // let parentUserMenu = JSON.parse((await axios.get("/user/getOneUserMenu")).data).menuInfo[0].child
                let parentUserMenu = (await axios.get("/user/getOneUserMenu")).data.menuInfo[0].child
                // console.log("更新前的 parentUserMenu", JSON.stringify(parentUserMenu, null, 2));
                if (parentData.uiType == "编辑用户") {
                    userUrl = "/user/editUser"
                    // console.log("parentData", JSON.stringify(parentData, null, 2));
                    $('[name= "userName"]').val(parentData.userName)
                    $('[name="userName"]').prop('disabled', true);
                    $('[name= "userPass"]').val("******")
                    $('[name="userPass"]').prop('disabled', true);
                    $('[name= "maxDeviceNum"]').val(parentData.maxDeviceNum)
                    $('[name= "beiZhu"]').val(parentData.beiZhu)
                    $('[name="checkStatus"]').prop('checked', parentData.checkStatus);
                    $('[name="touPing"]').prop('checked', parentData.touPing);
                    // 如果需要触发<select>元素的change事件，请添加以下代码
                    // selectElement.trigger('change');

                    let childUserMenu = parentData.menuData
                    parentUserMenu.forEach(function (menuItem) {//????
                        // 调用递归函数以更新 checked 属性
                        updateChecked(parentUserMenu, childUserMenu);
                    });
                    // form.render();
                }

                // console.log("更新后的 parentUserMenu", JSON.stringify(parentUserMenu, null, 2));

                tree.render({
                    elem: '#roleTreeId',
                    data: parentUserMenu,
                    showCheckbox: true,  // 是否显示复选框
                    onlyIconControl: true,  // 是否仅允许节点左侧图标控制展开收缩
                    id: 'treeId',
                    isJump: false, // 是否允许点击节点时弹出新窗口跳转
                    accordion: false,//是否开启手风琴模式
                    showLine: true,//是否开启节点连接线
                    customName: { // 自定义 data 字段名 --- 2.8.14+
                        children: 'child',
                    },
                    // click: function (obj) {
                    //   let data = obj.data;  //获取当前点击的节点数据
                    //   layer.msg('状态：' + obj.state + '<br>节点数据：' + JSON.stringify(data));
                    // }
                });


            })();




            form.on('submit(tijiao)', function (data) {
                //parentData
                // let taskName = data.elem.value
                let taskData = data.field

                let checkedData = tree.getChecked('treeId'); // 获取选中节点的数据

                // console.log("checkedData.length", checkedData.length);

                let newData = {
                    farterUserDeviceNu: parentData.userDeviceNum,//父账号(添加用)
                    farterMaxDeviceNum: parentData.maxDeviceNum,//父账号(添加用)
                    parentId: parentData.parent,//子账号的父id(编辑用)
                    oldMaxDeviceNum: parentData.maxDeviceNum,
                    userName: taskData.userName.replace(/\s/g, ""),
                    userPass: taskData.userPass,
                    maxDeviceNum: taskData.maxDeviceNum || 0,
                    telphone: taskData.telphone,
                    email: taskData.email,
                    beiZhu: taskData.beiZhu,
                    checkStatus: taskData.checkStatus ? true : false,
                    touPing: taskData.touPing ? true : false,
                    menuData: checkedData
                }

                if (newData.userName == "" || newData.userPass == "" || newData.userPass == "") {
                    layer.msg("用户名或密码或控数不能为空");
                    return false
                }

                if (!/^[A-Za-z][A-Za-z0-9]*$/.test(newData.userName)) {
                    layer.msg("用户名格式不正确")
                    return false
                }

                newData.maxDeviceNum = Number(newData.maxDeviceNum)
                // console.log("newData", JSON.stringify(newData, null, 2));
                axios.post(userUrl, newData)
                    .then(function (res) {
                        const resData = res.data
                        if (resData.code == 0) {
                            let iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                        } else {
                            console.log("添加/更新 用户失败", resData.msg);
                            layer.alert(resData.msg);
                        }
                    })
                    .catch(function (err) {
                        console.log("添加/更新 用户失败", e);
                        layer.alert(e.message);
                    });
                return false
            })


            function updateChecked(menuDic, oneMenuDic) {
                // 辅助函数：根据 id 查找元素
                function findById(id, items) {
                    for (const item of items) {
                        if (item.id === id) {
                            return item;
                        }
                        if (item.child && Array.isArray(item.child)) {
                            const found = findById(id, item.child);
                            if (found) return found;
                        }
                    }
                    return null;
                }

                // 递归函数：处理每个元素
                function processItems(menuItems, oneMenuItems) {
                    menuItems.forEach(item => {
                        const correspondingItem = findById(item.id, oneMenuItems);
                        // 如果有子元素，则设置 checked 为 false，否则根据是否找到对应项设置 checked
                        item.checked = item.child && Array.isArray(item.child) ? false : !!correspondingItem;

                        if (item.child && Array.isArray(item.child)) {
                            processItems(item.child, oneMenuItems); // 递归处理子元素
                        }
                    });
                }

                processItems(menuDic, oneMenuDic); // 开始处理 menuDic
            }

        });
    </script>


</body>

</html>